package edu.chinasoft.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public
class MybatisUtil {
    //通过静态块  初始化sqlSessionFactory
    private static
    SqlSessionFactory sqlSessionFactory=null;
    static {
        //加载配置文件，然后生成sqlsessionFactory
        InputStream InputStream=null;
        String resource = MyBatisConstant.RESOURCE;
        try {
            InputStream = Resources.getResourceAsStream( resource );
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build( InputStream );
    }
    //获取数据库连接对象
    public static
    SqlSession getSqlSession(boolean flag){
        SqlSession sqlSession=null;
        if (sqlSessionFactory!=null) {
            sqlSession = sqlSessionFactory.openSession( flag );
        }
        return sqlSession;
    }
    //关闭资源
    public static void close(SqlSession sqlSession){
        if (sqlSession!=null) {
            sqlSession.close();
        }
    }
}
